#include "register.h"
#include "tailor.h"
#include"httpmgr.h"
#include "ui_register.h"

#include <QDir>
#include <QProcess>

QString _getComputerUUID()//获得机器码
{
    QProcess process;
#ifdef Q_OS_WIN
    //    wmic csproduct get uuid
    QStringList mList;
    mList << "csproduct" << "get" << "uuid";
    process.start("wmic", mList);

    process.waitForFinished();
    QString ret = process.readAll();
    ret = ret.trimmed();

    QStringList dataList = ret.split("\r\n");

    if(dataList.length() != 2){
        return "";
    }
    return dataList[1].trimmed();
#endif

#ifdef Q_OS_LINUX
    // linux下可能需要先安装dmidecode：sudo apt install dmidecode
    // 然后本程序需要root权限才能获取到有效值
    QStringList mList;
    mList << "-s" << "system-uuid";
    process.start("dmidecode", mList);

    process.waitForFinished();
    QString ret = process.readAll();
    ret = ret.trimmed();

    return ret;
#endif
    return "";
}


Register::Register(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Register)
{
    initReq();
    ui->setupUi(this);

    connect(HttpMgr::GetInstance().get(), &HttpMgr::sig_reg_login_mod_finish, this, [this](QByteArray data, ReqID id, ErrorCodes err){
        req[id](data, err);
    });
    connect(this, &Register::guan, this, &Register::gggg);


    {
        QDir dir;
        if (!QDir("./data").exists()){
            dir.mkpath("./data");
        }
        if (!QDir("./data/other files").exists()){
            dir.mkpath("./data/other files");
        }
        if (!QDir("./data/chatting records").exists()){
            dir.mkpath("./data/chatting records");
        }
        if (!QDir("./data/head portrait").exists()){
            dir.mkpath("./data/head portrait");
        }
    }

}

Register::~Register()
{
    if (engine != nullptr){
        engine->deleteLater();
    }

    delete ui;
}

bool Register::NoSign_in()
{
    HttpMgr::GetInstance()->PostHttpReq(QUrl(url + "/exempt"), QByteArray(_getComputerUUID().toUtf8()), ReqID::ID_AUTO_LOGIN, Modules::REGISTERMO_LOGIN);
    return true;
}

void Register::on_pushButton_clicked()
{
    if (ui->lineEdit->text().isEmpty() || ui->lineEdit_2->text().isEmpty()){
        QMessageBox::warning(this, "警告", "请输入用户名和密码");
        return;
    }
    QJsonObject userObject;
    userObject["username"] = ui->lineEdit->text();
    userObject["password"] = ui->lineEdit_2->text();
    userObject["machineCode"] =  _getComputerUUID();
    userObject["bool"] = findFiles();

    HttpMgr::GetInstance()->PostHttpReq(QUrl(url + "/register"), QJsonDocument(userObject).toJson(), ReqID::ID_LOG_IN, Modules::REGISTERMO_LOGIN);
}

void Register::on_pushButton_2_clicked()
{
    if (engine != nullptr){
        qDebug() << "engine";
        return;
    }else if (ui->lineEdit->text().isEmpty() || ui->lineEdit_2->text().isEmpty()){
        QMessageBox::warning(this, "警告", "请输入用户名和密码");
        return;
    }

    engine = new QQmlApplicationEngine;
    // //对qml暴露tailor
    tailor = new Tailor;
    connect(tailor, &Tailor::accomplish, this,&Register::user_registration);
    connect(tailor, &Tailor::qmlClose, this, [this]{
        engine->deleteLater();
        tailor->deleteLater();
        tailor = nullptr;
        engine = nullptr;
    });
    engine->rootContext()->setContextProperty("tailor", tailor);
    engine->load(QUrl(QStringLiteral("qrc:/qml/Main.qml")));
}

//注册
void Register::user_registration(const QByteArray &ba)
{
    qDebug("发送11111");
    QJsonObject userObject;
    userObject["username"] = ui->lineEdit->text();
    userObject["password"] = ui->lineEdit_2->text();
    userObject["machineCode"] =  _getComputerUUID();
    userObject["head portrait"] = QJsonValue::fromVariant(ba.toBase64());
    HttpMgr::GetInstance()->PostHttpReq(QUrl(url + "/register/create"), QJsonDocument(userObject).toJson(), ReqID::ID_REG_USER, Modules::REGISTERMO_LOGIN);
}

void Register::gggg()
{
    disconnect(HttpMgr::GetInstance().get(), &HttpMgr::sig_reg_login_mod_finish, this, nullptr);
}

bool Register::findFiles()
{
    QDir dir("./data/head portrait");

    // 使用 QDir::entryList 查找文件
    QStringList fileList = dir.entryList(QStringList() << (ui->lineEdit->text() + "_HeadPortrait.jpg"), QDir::Files);
    if (fileList.isEmpty()) {
        return true;
    }
    return false;
}

void Register::initReq()
{
    req[ReqID::ID_REG_USER] = [this](QByteArray data, ErrorCodes err){
        switch(err){
        case ErrorCodes::StatusConflict:
            QMessageBox::warning(this, "警告", "用户名已存在");
            break;
        case ErrorCodes::StatusInternalServerError:
            QMessageBox::warning(this, "警告", "注册时发送500位置错误");
            break;
        default:
            QMessageBox::warning(this, "成功", "注册成功现在你可以登录了");
        };
    };
    req[ReqID::ID_LOG_IN] = [this](QByteArray data, ErrorCodes err){
        bool is = false;
        switch (err) {
        case ErrorCodes::StatusOK:
            myName = ui->lineEdit->text();
            if (findFiles()){
                QFile file("./data/head portrait/" + ui->lineEdit->text() + "_HeadPortrait.jpg");
                if (file.open(QIODevice::WriteOnly))
                {
                    file.write(data);
                    file.close();
                }
            }
            is = true;
            break;
        case ErrorCodes::StatusUnauthorized:
            QMessageBox::warning(this, "警告", "密码错误");
            break;
        case ErrorCodes::StatusNotFound:
            QMessageBox::warning(this, "警告", "用户不存在");
            break;
        case ErrorCodes::StatusConflict:
            QMessageBox::warning(this, "警告", "当前账号已登录");
            break;
        case ErrorCodes::StatusInternalServerError:
            QMessageBox::warning(this, "警告", "登录时发送错误");
            break;
        }

        if (is){
            emit guan();
            MainWindow *w = new MainWindow(myName);
            w->show();
            this->close();
            accept();
        }
    };
    req[ReqID::ID_AUTO_LOGIN] = [this](QByteArray data, ErrorCodes err){
        if (data != ""){
            MainWindow *w = new MainWindow(data);
            w->show();

            this->close();
            emit guan();
        }
    };
}
